﻿using B.S.Medical.Api.Read.Application.Command.Doctor;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Department;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Doctor
{
    public class SearchDoctorHandler : IRequestHandler<SearchDoctorCommand, ApiPageing<DoctorDTO>>
    {
        private readonly IBaseRepository<DoctorModel> doctorRepo;
        private readonly IBaseRepository<LabelModel> labelRepo;
        private readonly IBaseRepository<ManageModel> manageRepo;
        private readonly IBaseRepository<CampusModel> campusRepo;
        private readonly IBaseRepository<JobTitleModel> jobTitleRepo;
        private readonly IBaseRepository<DoctorLabelModel> doctorLabelRepo;
        private readonly ILogger<SearchDoctorHandler> logger;

        public SearchDoctorHandler(
            IBaseRepository<DoctorModel> doctorRepo,
            IBaseRepository<LabelModel> labelRepo,
            IBaseRepository<ManageModel> manageRepo,
            IBaseRepository<CampusModel> campusRepo,
            IBaseRepository<JobTitleModel> jobTitleRepo,
            IBaseRepository<DoctorLabelModel> doctorLabelRepo,
            ILogger<SearchDoctorHandler> logger)
        {
            this.doctorRepo = doctorRepo;
            this.labelRepo = labelRepo;
            this.manageRepo = manageRepo;
            this.campusRepo = campusRepo;
            this.jobTitleRepo = jobTitleRepo;
            this.doctorLabelRepo = doctorLabelRepo;
            this.logger = logger;
        }

        public Task<ApiPageing<DoctorDTO>> Handle(SearchDoctorCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiPageing<DoctorDTO> res=new ApiPageing<DoctorDTO>();
                // 获取所有未删除的医生、科室、校区和标签数据
                var doctors = doctorRepo.GetAll().Where(a => !a.IsDeleted);
                var manages = manageRepo.GetAll().Where(a => !a.IsDeleted);
                var campuses = campusRepo.GetAll().Where(a => !a.IsDeleted);
                var labels = labelRepo.GetAll().Where(a => !a.IsDeleted);
                var doctorlaber=doctorLabelRepo.GetAll().Where((a) => !a.IsDeleted);
                var jobTitle= jobTitleRepo.GetAll().Where(a => !a.IsDeleted);

                // 条件判断科室
                if (request.DepartmentId != 0)
                {
                    doctors = doctors.Where(a => a.DepartmentId == request.DepartmentId);
                }

                // 条件判断医生名称
                if (!string.IsNullOrEmpty(request.DoctorName))
                {
                    doctors = doctors.Where(a => a.DoctorName.Contains(request.DoctorName));
                }

                // 使用LINQ连接查询获取完整的医生信息
                var query = from doctor in doctors
                            join manage in manages on doctor.DepartmentId equals manage.Id into deptJoin
                            from dept in deptJoin.DefaultIfEmpty()
                            join campus in campuses on doctor.CampusId equals campus.Id into campusJoin
                            from camp in campusJoin.DefaultIfEmpty()
                            join job in jobTitle on doctor.JobTitleId equals job.Id
                            //join dlaber in doctorlaber on doctor.Id equals dlaber.DoctorId
                            //join laber in labels on dlaber.LaberId equals laber.Id
                            select new DoctorDTO
                            {
                                Id = doctor.Id,
                                DoctorName = doctor.DoctorName,
                                DepartmentId = doctor.DepartmentId,
                                DepartmentName = dept.DepartmentName ?? string.Empty,
                                CampusId = doctor.CampusId,
                                CampusName = camp.CampusName ?? string.Empty,
                                JobTitle =job.JobTitle,
                                Briefly = doctor.Briefly,
                                Photo = doctor.Photo,
                                Status = doctor.Status,
                                Labels = (from dl in doctorlaber where dl.DoctorId == doctor.Id join l in labels on dl.LaberId equals l.Id select new LabelModel { Id = l.Id, Label = l.Label }).ToList(),
                            };

                // 分页处理，按Id倒序（最新添加的在前）
                int totalCount = query.Count();
                var items = query
                    .OrderByDescending(x => x.Id)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();

                // 构建返回结果
                res.Code = ApiEnum.Success;
                res.Msg = "查询医生条件列表分页成功";
                res.PageData = items;
                res.TotaCount = totalCount;
                res.TotaPage = (int)Math.Ceiling(res.TotaCount/request.PageSize*1.0);

                return Task.FromResult(res);
            }
            catch (System.Exception ex)
            {
                logger.LogError(ex, "搜索医生信息时发生错误");
                throw;
            }
        }
    }
}
